package com.dx.mes.service.query.service;

import com.dx.common.table.ppt.*;
import com.dx.mes.common.dao.*;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.query.service.IFippinqprdService;
import com.dx.mes.facade.query.tx.Fipinqprd.FipinqprdI;
import com.dx.mes.facade.query.tx.Fipinqprd.FipinqprdO;
import com.dx.mes.facade.query.tx.Fipinqprd.FipinqprdOA;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

import static com.dx.mes.common.bean.def.GenericDef.*;
import static com.dx.mes.common.bean.def.GenericDef.E_FIPINQSHT_INVALID_INPUT;

/**
 * Created by Administrator on 2018/3/6/006.
 */
@Service("fipinqprdService")
public class FippinqprdService implements IFippinqprdService {
    private LogUtils logUtils;
    private static final String TX_NAME = "FIPINQPRD";

    @Autowired
    private IRetPrdInfoDao retPrdInfoDao;
    @Autowired
    private IRetWODao retWoDao;
    @Autowired
    private IBisOpeDao bisOpeDao;
    @Autowired
    private IBisMdlGrdDao bisMdlGrdDao;
    @Autowired
    private IBisToolGrDao bisToolGrDao;
    @Autowired
    private IBisPathDao bisPathDao;
    @Autowired
    private IBisPamDao bisPamDao;
    @Autowired
    private IRetLineWoDao retLineWoDao;
    @Autowired
    private IBisMdlDefDao bisMdlDefDao;
    @Autowired
    private IBisToolDao bisToolDao;

    public String subMainProc(String evt_no, String strInMsg) {
        AppContext.clear();
        AppContext.setCurrServiceName(FipinqshtService.class.getSimpleName());
        AppContext.setCurrEventNumber(evt_no);
        logUtils = new LogUtils(FipinqshtService.class);
        logUtils.info("[InTrx:" + strInMsg + "]");

        String outMsg = "";
        FipinqprdI inTrx = new FipinqprdI();
        FipinqprdO outTrx = new FipinqprdO();

        outTrx.setTrx_id(TX_NAME);
        outTrx.setType_id(TRX_OUT);
        outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));

        try {
            inTrx = JacksonUtil.fromJson(strInMsg, FipinqprdI.class);

            subMainProc2(inTrx.getAction_flg().toCharArray()[0], inTrx, outTrx);
            if (!outTrx.getRtn_code().equals(RETURN_CODE_OK)) {
                TransactionAspectSupport.currentTransactionStatus()
                        .setRollbackOnly();
            } else {
                retPrdInfoDao.flushCurSession();
            }
        } catch (Exception ex) {
            outTrx.setRtn_mesg(ex.toString());
            outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
            logUtils.error(Util.stackTraceToString(ex));
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
        } finally {
            outMsg = JacksonUtil.toJSONStr(outTrx);
            logUtils.info("[OutTrx:" + outTrx + "]");
        }
        return outMsg;
    }

    private void subMainProc2(char actionType, FipinqprdI inTrx, FipinqprdO outTrx) {
        switch (actionType) {
            case 'Q': {
                getPrdInfo(inTrx, outTrx);
                break;
            }
            default: {
                String gszMsgBuf = "Invalide type input: [" + actionType + "]";

                outTrx.setRtn_code(String.valueOf(E_FIPINQSHT_INVALID_INPUT));
                outTrx.setRtn_mesg(gszMsgBuf);
                return;
            }
        }
    }

    private void getPrdInfo(FipinqprdI inTrx, FipinqprdO outTrx) {
        List<FipinqprdOA> oaryAList = new ArrayList<>();
        String prd_seq_id = inTrx.getPrd_seq_id();
        String line_id = inTrx.getLine_id();
        String tool_id = inTrx.getTool_id();
        if (StringUtils.isEmpty(prd_seq_id)) {
            String gszMsgBuf = "屏体代码不能为空!";
            outTrx.setRtn_code(String.valueOf(E_READ_NOT_FOUND + E_RET_PRD_INFO));
            outTrx.setRtn_mesg(gszMsgBuf);
            return;
        }
        Ret_prd_info ret_prd_info = retPrdInfoDao.get(prd_seq_id);
        if (null == ret_prd_info) {
            String gszMsgBuf = "屏体代码为[" + prd_seq_id + "]的屏体信息不存在！";
            outTrx.setRtn_code(String.valueOf(E_READ_NOT_FOUND + E_RET_PRD_INFO));
            outTrx.setRtn_mesg(gszMsgBuf);
            return;
        }
        outTrx.setPrd_seq_id(ret_prd_info.getPrd_seq_id());
        outTrx.setPrd_stat(ret_prd_info.getPrd_stat());
        outTrx.setPrd_qty(ret_prd_info.getPrd_qty());
        outTrx.setWo_id_fk(ret_prd_info.getWo_id_fk());
        outTrx.setPrd_grade(ret_prd_info.getPrd_grade());
        outTrx.setMdl_id_fk(ret_prd_info.getMdl_id_fk());
        if (!Util.isSpaceCheck(ret_prd_info.getWo_id_fk())) {
            Ret_wo ret_wo = retWoDao.get(ret_prd_info.getWo_id_fk());
            if (null != ret_wo) {
                outTrx.setWo_cate(ret_wo.getWo_cate());
            }
        }
        if (!Util.isSpaceCheck(ret_prd_info.getPrd_grade())) {
            outTrx.setPrd_judge(ret_prd_info.getExt_9());
            outTrx.setPrd_grade(ret_prd_info.getPrd_grade());
        }
        if (!Util.isSpaceCheck(tool_id)) {
            String hql1 = "from Bis_tool_gr where 1=1 and " +
                    "tool_id_fk='" + tool_id + "'";
            List<Bis_tool_gr> bis_tool_grs = bisToolGrDao.find(hql1);
            bis_tool_grs.get(0).getId().getToolg_id();
            if (!Util.isSpaceCheck(bis_tool_grs.get(0).getId().getToolg_id())) {
                String hql2 = "from Bis_ope where 1=1 and " +
                        "toolg_id_fk='" + bis_tool_grs.get(0).getId().getToolg_id() + "'";
                List<Bis_ope> bis_opes = bisOpeDao.find(hql2);

                String hql = "FROM Ret_line_wo WHERE line_id_fk='" + line_id
                        + "' and ope_id_fk='" + bis_opes.get(0).getId().getOpe_id()
                        + "' and wo_id_fk='" + ret_prd_info.getWo_id_fk() + "'";
                List<Ret_line_wo> line_woList = retLineWoDao.find(hql);
                if (line_woList.size() == 0) {
                    outTrx.setRtn_code(E_RET_LINE_WO + E_READ_NOT_FOUND + "");
                    outTrx.setRtn_mesg("线别["+line_id+"]，站点["+bis_opes.get(0).getId().getOpe_id()+"]，工单["+ret_prd_info.getWo_id_fk()+"]信息未设定，请处理");
                    return;
                }
                Ret_line_wo ret_line_wo = line_woList.get(0);
                if (_NO.equals(ret_line_wo.getValid_flg())) {
                    outTrx.setRtn_code(E_RET_LINE_WO + E_READ_NOT_FOUND + "");
                    outTrx.setRtn_mesg("线别["+line_id+"]，站点["+bis_opes.get(0).getId().getOpe_id()+"]，工单["+ret_prd_info.getWo_id_fk()+"]信息未激活,请处理");
                    return;
                }

                String hql0 = "from Ret_wo where 1=1 and wo_id='" + ret_prd_info.getWo_id_fk() + "'";
                List<Ret_wo> ret_wos = retWoDao.find(hql0);
                if (!Util.isSpaceCheck(ret_wos.get(0).getPath_id_fk())) {
                    String hql3 = "from Bis_path where 1=1 and path_id_fk='" + ret_wos.get(0).getPath_id_fk() + "'";
                    List<Bis_path> bis_paths = bisPathDao.find(hql3);
                    for (Bis_path bis_path : bis_paths) {

                        //获取站点对应的设备
                        Bis_opeId opeId = new Bis_opeId();
                        opeId.setOpe_id(bis_path.getCr_ope_id_fk());
                        opeId.setOpe_ver(bis_path.getCr_ope_ver_fk());
                        Bis_ope bis_ope = bisOpeDao.get(opeId);
                        if (bis_ope == null) {// TODO 判断站点设定
                            outTrx.setRtn_code(E_BIS_OPE + E_READ_NOT_FOUND + "");
                            outTrx.setRtn_mesg("站点["+bis_path.getCr_ope_id_fk()+"]信息不存在");
                        }
                        List<Bis_tool_gr> bis_tool_grList = bisToolGrDao.find("from Bis_tool_gr where 1=1 and " +
                                "toolg_id='" + bis_ope.getToolg_id_fk() + "'");
                        for (Bis_tool_gr bis_tool_gr : bis_tool_grList) {
                            FipinqprdOA oary1 = new FipinqprdOA();
                            Bis_tool bis_tool = bisToolDao.get(bis_tool_gr.getId().getTool_id_fk());
                            if (bis_tool != null && inTrx.getLine_id().equals(bis_tool.getBay_id())) {
                                oary1.setTool_id(bis_tool.getTool_id());
                                if ("3".equals(bis_path.getSkip_flg())) {
                                    oary1.setSkip_flg("1");
                                } else {
                                    oary1.setSkip_flg("0");
                                }
                                //获取Recipe信息
                                String hql4 = "FROM Bis_pam WHERE active_flg='Y' and tool_id_fk='"
                                        + bis_tool.getTool_id() +
                                        "' and path_id_fk='" + ret_wos.get(0).getPath_id_fk() +
                                        "'and ope_id_fk='" + bis_path.getCr_ope_id_fk() + "'";
                                List<Bis_pam> bis_pam = bisPamDao.find(hql4);
                                if (bis_pam != null && bis_pam.size() > 0) {
                                    oary1.setRecipe_no(bis_pam.get(0).getRecipe_id());
                                } else {
                                    oary1.setRecipe_no("0");
                                }
                                oaryAList.add(oary1);
                            }
                        }
                    }
                }
            }
        }
        outTrx.setOaryA(oaryAList);
        outTrx.setRtn_code(RETURN_CODE_OK);
        outTrx.setRtn_mesg(RETURN_MESG_OK);
    }
}





